package cn.com.infohold.smartcity.update;

import android.text.TextUtils;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Mr.Fan on 2017/1/30.
 */

public class ApkVersion implements Serializable {
    protected static final Pattern PATTERN = Pattern.compile("-([a-zA-Z]+)-([a-zA-Z]+)-(\\d+)\\.(\\d+)\\.(\\d+)-(\\d+).apk$");
    private final String name;
    private final int versionCode;

    private final int major;
    private final int minor;
    private final int fixed;

    public ApkVersion(String name) {
        this(name, null);
    }

    public ApkVersion(String name, Integer vCode) {
        this.name = name;
        int code = vCode != null ? vCode : 0;
        if (!TextUtils.isEmpty(name)) {
            Matcher matcher = PATTERN.matcher(name);
            if (matcher.find()) {
                major = Integer.parseInt(matcher.group(3));
                minor = Integer.parseInt(matcher.group(4));
                fixed = Integer.parseInt(matcher.group(5));
                versionCode = Math.max(code, Integer.parseInt(matcher.group(6)));
                return;
            }
        }
        versionCode = code;
        major = 0;
        minor = 0;
        fixed = 0;
    }

    public String getVersionName() {
        return major + "." + minor + "." + fixed;
    }


    public int getVersionCode() {
        return versionCode;
    }

    public int compare(String versionName) {
        return compare(new ApkVersion(versionName));
    }

    public int compare(ApkVersion version) {
        if (version == null)
            return 1;
        if (major > version.major
                || (major >= version.major && minor > version.minor)
                || (major >= version.major && minor >= version.minor && fixed > version.fixed)) {
            return 1;
        } else if (major == version.major && minor == version.minor && fixed == version.fixed) {
            return 0;
        }
        return -1;
    }

}
